'use strict'
const EventEmitter = require('events')
const DyRoom = require('./douyu/dyroom')
const PandaRoom = require('./panda/pandaroom')
class RoomManage extends EventEmitter {
  constructor () {
    super()
    this.rooms = new Map()
    setInterval(function () {
      this._count()
    }.bind(this), 15 * 1000)
  }
  _count () {
    var count = 0
    this.rooms.forEach(function (room) {
      count += room.count
    })
    console.log(`监控房间数:${this.rooms.size}监控总数:${count}`)
  }
  add (platform, roomId, socketId) {
    if (!this.rooms.has(this._getKey(platform, roomId))) {
      let room = null
      switch (platform) {
        case 'dy':
          room = new DyRoom(roomId)
          break
        case 'panda':
          room = new PandaRoom(roomId)
          break
        default:
      }
      if (room) {
        room.count += 1
        room.on('init', this._initRoom.bind(this, platform, roomId, socketId))
        room.on('data', this._roomMsg.bind(this, platform, roomId))
        room.on('update', this._updateRoom.bind(this, platform, roomId))
        this.rooms.set(this._getKey(platform, roomId), room)
      }
    } else {
      let room = this.rooms.get(this._getKey(platform, roomId))
      room.count += 1
      this.emit('init', platform, roomId, socketId, room.info)
    }
  }
  _getKey (platform, roomId) {
    platform = platform || 'dy'
    return platform.concat('_').concat(roomId)
  }
  remove (platform, roomId) {
    let key = this._getKey(platform, roomId)
    let room = this.rooms.get(key)
    if (room) {
      room.count -= 1
      if (room.count === 0) {
        room.destroy()
        this.rooms.delete(key)
      }
    }
  }
  _initRoom (platform, roomId, socketId, data) {
    this.emit('init', platform, roomId, socketId, data)
  }
  _updateRoom (platform, roomId, data) {
    this.emit('update', platform, roomId, data)
  }
  _roomMsg (platform, roomId, msg) {
    this.emit('data', platform, roomId, msg)
  }
}
module.exports = new RoomManage()
